/* eslint indent: ["off"] */
/* eslint space-before-function-paren: ["off"] */

// 引入 lodash 库，用于数据处理和操作
const _ = require('lodash')

// 引入 fs 模块，用于文件系统操作
const fs = require('fs')
// 引入 path 模块，用于处理文件和目录路径
const path = require('path')
// 引入 esm 库，用于在 Node.js 中支持 ES6 模块
const esm = require('esm')
// 使用 esm 配置来加载模块
const requireModule = esm(module)

// 获取项目根目录
const DB_DEMO_DIR = path.join(__dirname, '../../db-demo')
// helpers 目录
const JSON_DIR = path.join(DB_DEMO_DIR, 'json')

const { calcHot } = require('../utils/calcHot')

// 获取项目根目录
const ROOT_DIR = path.join(__dirname, '../..')
// helpers 目录
const HELPERS_DIR = path.join(ROOT_DIR, 'helpers')

// 地区
const { region } = requireModule(path.join(ROOT_DIR, '/src/utils/modules/settings.js'))

const { calcAccuracySummary } = require(path.join(HELPERS_DIR, 'calcAccuracySummary.js'))

exports.getTop32 = async (req, res) => {
  const { region } = req.query
  const { leadingAccuracyList, trailingAccuracyList, leadingList, trailingList, numberCounts, accuracySummary } =
    calcHot(region)

  res.json({
    code: 200,
    message: '成功',
    data: {
      leadingAccuracyList,
      trailingAccuracyList,
      leadingList,
      trailingList,
      numberCounts,
      accuracySummary
    }
  })
}

exports.getExample = async (req, res) => {
  // eslint-disable-next-line no-irregular-whitespace
  fs.readFile(path.join(JSON_DIR, `​${region}-Steps-09-allList.json`), 'utf8', (err, jsonString) => {
    if (err) {
      console.error('读取文件失败:', err)
      return
    }
    try {
      const tableData = JSON.parse(jsonString).slice(200)
      const accuracySummary = calcAccuracySummary(tableData.filter((item) => item.accuracy != null).map((item) => item.accuracy))
      res.json({
        code: 200,
        message: '成功',
        data: {
          tableData,
          accuracySummary
        }
      })

      console.timeEnd('计算结束')
    } catch (parseErr) {
      console.error('解析 JSON 失败:', parseErr)
    }
  })
}
